define(function () {
  /**
   * 画三个点连线，计算角度
   * @param {Cesium.Viewer} viewer 基本视图
   * @param {Cesium.ScreenSpaceEventHandler} handler 屏幕监听事件
   * @param {ReminderPanel} reminder 信息提示类
   * @param {Cesium.CustomDataSource}measureEntities 标绘实体集合
   */
  let calcAngle = function (viewer, handler, reminder, measureEntities) {
    let activeShapePoints = []                      //标绘点集合

    /**
     *添加线实体
     *@param {Cesium.Cartesian3 []} positionData 线段数组
     */
    function drawShape(positionData) {
      if (positionData.length >= 2)
        return measureEntities.entities.add({
          polyline: {
            positions: positionData,
            width: 3,
          },
        })
    }

    /**
     *添加点
     *@param {Cesium.Cartesian3} worldPosition
     */
    function createPoint(worldPosition) {
      return measureEntities.entities.add({
        description: 'point',
        position: worldPosition,
        point: {
          color: Cesium.Color.WHITE,
          pixelSize: 5,
        },
      })
    }

    //左键点击，当长度等于二连线，长度等于三求角度并连线
    handler.setInputAction((event) => {
      reminder.show('正在测量角度')
      let earthPosition = viewer.camera.pickEllipsoid(event.position, viewer.scene.globe.ellipsoid)
      if (activeShapePoints.length === 0) {
        createPoint(earthPosition)
      }
      if (activeShapePoints.length === 3) {
        activeShapePoints = []
      }
      activeShapePoints.push(earthPosition)
      if (activeShapePoints.length === 3) {
        reminder.show('角度为：' + getAngle(activeShapePoints).toFixed(2) + '°')
      }
      drawShape(activeShapePoints.slice(-2))
      createPoint(earthPosition)
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK)

    //右键点击重置数组
    handler.setInputAction(function (event) {
      activeShapePoints = []
    }, Cesium.ScreenSpaceEventType.RIGHT_CLICK)
  }

  /**
   *求角度
   *@param {Cesium.Cartesian3[]} activeShapePoints 传入含有xyz属性的坐标对象数组
   */
  function getAngle(activeShapePoints) {
    let angle
    activeShapePoints.forEach(function (val, index) {
      if (index > 0 && index < activeShapePoints.length - 1) {
        let x1 = activeShapePoints[index - 1].x
        let x2 = activeShapePoints[index].x
        let x3 = activeShapePoints[index + 1].x
        let y1 = activeShapePoints[index - 1].y
        let y2 = activeShapePoints[index].y
        let y3 = activeShapePoints[index + 1].y
        let z1 = activeShapePoints[index - 1].z
        let z2 = activeShapePoints[index].z
        let z3 = activeShapePoints[index + 1].z
        let _P1P2 = Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2 + (z2 - z1) ** 2)
        let _P2P3 = Math.sqrt((x3 - x2) ** 2 + (y3 - y2) ** 2 + (z3 - z2) ** 2)
        let P = (x1 - x2) * (x3 - x2) + (y1 - y2) * (y3 - y2) + (z1 - z2) * (z3 - z2)

        angle = (Math.acos(P / (_P1P2 * _P2P3)) / Math.PI) * 180
      }
    })
    return angle
  }
  return calcAngle
})